<template>
  <div ref="echartDom"></div>
</template>

<script setup>
import {ref, defineProps, onMounted, onUnmounted, inject, shallowRef, defineExpose} from 'vue'
import {pxToRem} from "@/utils/index";

const echarts = inject('echarts');
const props = defineProps({
  radarData: {
    type: Object,
    default: () => {
    }
  },
  dialogData: {
    type: Object,
    default: () => ({
      fontSizeTimes: 1
    })
  }
});

const echartDom = ref(null);
const myChart = shallowRef(null);

const initEchart = () => {
  if (echartDom.value) {
    myChart.value = echarts.init(echartDom.value);
    let option = {
      legend: {
        type: 'scroll',
        data: props?.radarData?.legendData,
        orient: 'vertical',
        icon: "roundRect",
        right: '2%',
        top: 'center',
        padding: [0, 0, pxToRem(30 * props?.dialogData?.fontSizeTimes)],
        itemGap: pxToRem(10 * props?.dialogData?.fontSizeTimes),
        itemWidth: pxToRem(12 * props?.dialogData?.fontSizeTimes),
        itemHeight: pxToRem(12 * props?.dialogData?.fontSizeTimes),
        textStyle: {
          fontSize: pxToRem(11 * props?.dialogData?.fontSizeTimes),
          color: 'white',
        },
        pageButtonItemGap: 0,
        pageIconColor: 'white',
        pageIconInactiveColor: '#A9A9A9',
        pageIconSize: pxToRem(10 * props?.dialogData?.fontSizeTimes),
        pageTextStyle: {
          color: 'white',
          fontSize: pxToRem(10 * props?.dialogData?.fontSizeTimes),
        },
      },
      radar: {
        center: ["35%", "50%"],
        radius: "60%",
        splitNumber: 5,
        name: {
          textStyle: {
            color: '#03DBFF',
            fontSize: pxToRem(12 * props?.dialogData?.fontSizeTimes),
          },
        },
        indicator:  props?.radarData?.indicatorData
      },
      series: [
        {
          type: 'radar',
          data: props?.radarData?.seriesData
        }
      ]
    }
    option && myChart.value.setOption(option, true);

    myChart.value.on("legendselectChanged", (params) => {
      event.stopPropagation();
    });

    myChart.value.on('legendscroll', (params) => {
      event.stopPropagation();
    });
  }
}

const updateChart = () => {
  if (myChart.value) {
    myChart.value.dispose(); // 销毁旧图表实例
  }
  initEchart();
};

const disposeChart = () => { // 销毁旧图表实例
  if (myChart.value) {
    myChart.value.dispose(); // 销毁旧图表实例
  }
}

defineExpose({
  updateChart,
  disposeChart
})

onMounted(() => {
  initEchart();
  window.addEventListener("resize", updateChart);
})

onUnmounted(() => {
  window.removeEventListener("resize", updateChart);
})
</script>

<style scoped lang="less">
.h150 {
  height: 150px;
}
.dialog-h150 {
  width: 1120px;
  height: 500px;
}
</style>